package work.javac.common.database.utils;

import work.javac.common.ConfigUtil;
import work.javac.common.Log;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;

public class DBUtils {

    private static Map<Connection, String> CONNS = new LinkedHashMap<>();

    public static String getSchema(Connection conn) {
        return CONNS.get(conn);
    }

    public static Connection getConn(String name) {
        String driver = ConfigUtil.get(name + ".driver");
        String url = ConfigUtil.get(name + ".url");
        String username = ConfigUtil.get(name + ".username");
        String password = ConfigUtil.get(name + ".password");
        if(driver == null || url == null || username == null || password == null){
            Log.err("有数据库参数为空或数据源传入错误!");
            Log.err("数据源名称:%s; driver:%s; url:%s; username:%s; password:%s", name, driver, url, username, password);
            System.exit(1);
        }
        Properties prop = new Properties();
        prop.setProperty("user", username);
        prop.setProperty("password", password);
        prop.setProperty("remarks", "true");
        prop.setProperty("useInformationSchema", "true");
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            Log.err("数据源%s,找不到%s驱动包!", name, driver);
            Log.err(e.getMessage());
            System.exit(1);
        }
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, prop);
            CONNS.put(conn, ConfigUtil.get(name + ".schema"));
        } catch (SQLException e) {
            Log.err("数据源%s,连接失败!请检查配置文件!", name);
            Log.err(e.getMessage());
            System.exit(1);
        }
        return conn;
    }

//    public static void close(Connection conn){
//        if(conn != null){
//            try {
//                conn.close();
//            } catch (SQLException e) {
//                Log.err(e.getMessage());
//            }
//        }
//    }
}
